// ControlGun.js

cc.Class({
    extends: cc.Component,

    properties: {
        mBullet: cc.Prefab
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() { },

    start() {
        this.node.on('touchstart', this.onTouchStart, this);
        this.node.on('touchmove', this.onTouchMove, this);
        this.node.on('touchend', this.ontouchEnd, this);
    },

    // update (dt) {},

    onTouchStart(event) {    // 每次点击之前，都要把结果关掉
        var successLabel = this.node.parent.getChildByName('successLabel');
        successLabel.active = false;

        var failLabel = this.node.parent.getChildByName('failLabel');
        failLabel.active = false;
    },

    onTouchMove(event) {    // 控制节点在屏幕范围内左右移动
        let rangePos = event.getDelta();

        this.node.x += rangePos.x;

        let minX = -this.node.parent.width / 2 + this.node.width / 2;
        let maxX = Math.abs(minX);

        let currentPos = this.node.getPosition();

        if (currentPos.x < minX) {
            currentPos.x = minX;
        } else if (currentPos.x > maxX) {
            currentPos.x = maxX;
        }

        this.node.setPosition(currentPos);
    },

    ontouchEnd(event) {    // 松开时发射子弹
        console.log('发射子弹');

        let bullet = cc.instantiate(this.mBullet);
        bullet.parent = this.node.parent;

        let currentPos = this.node.getPosition();

        bullet.parent = this.node.parent;
        bullet.setPosition(currentPos);
    }
});
